from os import spawnl, P_NOWAIT
from os import waitpid as waitForProcessExit

from signal import signal as installSignalHandler

from select import error as SelectError
from errno import EINTR, ECHILD

def kill(pid):
    """kill function for Win32"""
    import win32api
    handle = win32api.OpenProcess(1, 0, pid)
    return (0 != win32api.TerminateProcess(handle, 0))

def isInterruptError(e):
    return (e.args[0] == EINTR)
def isReapComplete(e):
    return (e.args[0] == ECHILD)

class NativePlatform:
    def __init__(self, config):
        self.wgetbin = config.wgetbin

        # XXX How to install SIGCHLD?
        # installSignalHandler(self.reap)

    def reap(self, signr, stack_frame):
        if signr == theReapSignal:
            for (pid, status) in cleanupChildProcesses():
                pass

    def cleanupChildProcesses(self):
        while True:
            try: (pid, status) = waitForProcessExit(-1, WNOHANG)
            except OSError, e:
                if isReapComplete(e):
                    break

                reraise()

            yield (pid, status >> 8)

    # Not really needed, since using spawn*
    ##    def safe_shell_string(self, string):
    ##        return "'%s'" % string

    def spawn_download(self, kwd):
        args = ['-c', kwd['url']]
        if 'filename' in kwd:
            args.append('-O')
            args.append(kwd['filename'])

        return spawnl(P_NOWAIT, self.wgetbin, *args)

    def kill_download(self, pid):
        send_signal(pid, theKillSignal)
    def pause_download(self, pid):
        send_signal(pid, thePauseSignal)
    def resume_download(self, pid):
        send_signal(pid, theResumeSignal)
